package com.hk.system.config;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hk.domain.entity.User;
import com.hk.domain.service.UserService;
import com.hk.security.authentication.ProductUserInfo;
import dubhe.token.core.model.UserInfo;
import lombok.Builder;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Collection;
import java.util.Optional;

/**
 * @author miaoj
 */
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final Optional<User> userOptional = userService.getOneOpt(Wrappers.<User>lambdaQuery().eq(User::getAccount, username));
        if (userOptional.isEmpty()) {
            throw new UsernameNotFoundException(username);
        }
        final User user = userOptional.get();
        return LoginUserDetails.builder()
                .username(username)
                .password(user.getPassword())
                .enabled(true)
                .userInfo(ProductUserInfo
                        .builder()
                        .loginName(username)
                        .name(user.getName())
                        .id(user.getId())
                        .type(user.getType())
                        .authenticated(true)
                        .build())
                .build();
    }

    @Getter
    @Builder
    public static class LoginUserDetails implements UserDetails {

        private static final long serialVersionUID = 5239252221231696342L;

        private Collection<? extends GrantedAuthority> authorities;

        private final String password;

        private final String username;

        private UserInfo userInfo;

        @Builder.Default
        private boolean accountNonExpired = true;

        @Builder.Default
        private boolean accountNonLocked = true;

        @Builder.Default
        private boolean credentialsNonExpired = true;

        private final boolean enabled;
    }

}
